package com.example.take_out_dish.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.take_out_dish.common.Result;
import com.example.take_out_dish.entity.Category;
import com.example.take_out_dish.entity.Dish;
import com.example.take_out_dish.exceptions.BusinessException;
import com.example.take_out_dish.exceptions.enumetation.ResponseEnum;
import com.example.take_out_dish.service.CategoryService;
import com.example.take_out_dish.service.DishService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author yyyyys
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private DishService dishService;

    @GetMapping("page")
    public Result<Page<Category>> page(int page, int pageSize,String name,String type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(name)){
            wrapper.like(Category::getName, name);
        }
        if (StrUtil.isNotBlank(type)) {
            wrapper.like(Category::getType, type);
        }
        Page<Category> pageInfo= categoryService.page(new Page<>(page, pageSize),wrapper);
        return Result.success(pageInfo);
    }

    @PostMapping()
    public Result<Boolean> save(@RequestBody Category category){
        return Result.success(categoryService.save(category));
    }

    @DeleteMapping()
    public Result<Object> deleteById(String id){
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,id);
        long count = dishService.count(wrapper);
        if (count > 0){
            throw new BusinessException(ResponseEnum.CATEGORY_ERROR);
        }
        categoryService.removeById(id);
        return Result.success();
    }

    @PutMapping()
    public Result<Object> update(@RequestBody Category category){
        categoryService.updateById(category);
        return Result.success();
    }

    @GetMapping("list")
    public Result<Object> categoryList(@RequestParam("type") int type){
        List<Category> categories = categoryService.getCategorIdAndName(type);
        System.out.println("categories:{}"+categories);
        log.info("categories:{}",categories);
        return Result.success(categories);
    }
}
